package com.tgu.home_action.service.utils;

import com.tgu.home_action.pojo.TrackPoint;

import java.util.ArrayList;
import java.util.List;

public class DouglasPeuckerUtils {
    private final static double minDis=0.5;


    public static List<TrackPoint> dp(List<TrackPoint> trackPoints){
        if (trackPoints.size()==0||trackPoints.size()==1){
            return trackPoints;
        }
        //压缩后保留下的点
        List<TrackPoint> isSave=new ArrayList<>();
        isSave.add(trackPoints.get(0));
        isSave.add(trackPoints.get(trackPoints.size()-1));
        recursionDP(trackPoints,isSave,0,trackPoints.size()-1);
        //按时间排序
        isSave.sort((trackPoint, t1) -> {
            return trackPoint.getCreateAt().after(t1.getCreateAt())?1:-1;
        });
        System.out.println(isSave.size());
        return isSave;

    }

    public static void recursionDP(List<TrackPoint> trackPoints,List<TrackPoint> isSave,int index,int end){
        double sideDis=StringService.getDistance(trackPoints.get(index).getLatitude(),trackPoints.get(index).getLongitude(),
                trackPoints.get(end).getLatitude(),trackPoints.get(end).getLongitude());
        if(end-index==1){
            return;
        }
        double maxDis=0.0;
        int node=0;
        for(int i=index+1;i<end;i++){
            double dis=pointLineDis(trackPoints.get(i).getLatitude(),trackPoints.get(i).getLongitude(),
                    trackPoints.get(index).getLatitude(),trackPoints.get(index).getLongitude(),
                    trackPoints.get(end).getLatitude(),trackPoints.get(end).getLongitude(),sideDis);
            if(dis>=maxDis){
                node=i;
                maxDis=dis;
            }
        }
        if(maxDis>=minDis){
            System.out.println(trackPoints.get(node));
            isSave.add(trackPoints.get(node));
            recursionDP(trackPoints,isSave,index,node);
            recursionDP(trackPoints,isSave,node,end);
        }
    }

    /**
     * 计算点到两点连线的距离
     */
    public static double pointLineDis(double lng, double lat, double lng1, double lat1, double lng2, double lat2,double sideDis) {
        double sideA=StringService.getDistance(lat,lng,lat1,lng2);
        double sideB=StringService.getDistance(lat,lng,lat2,lng2);
        double p=(sideA+sideB+sideDis)/2;
        double S=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideDis));
        return 2*S/sideDis;
    }
}
